#include "common.h"
#include <errno.h>

void *read_routine(void *args)
{
    //printf("read_routine\n");

    int msgid = *(int *)args;

    struct msgbuf recvbuf;

    while (true)
    {
        memset(&recvbuf, 0, sizeof(recvbuf));

        ssize_t n = msgrcv(msgid, &recvbuf, sizeof(recvbuf.mtext), CLIENTTYPE, 0);
        printf("server# type=%ld text=%s\n", recvbuf.mtype, recvbuf.mtext);
    }

    return NULL;
}

void *write_routine(void *args)
{
    //printf("write_routine\n");

    int msgid = *(int *)args;

    struct msgbuf sendbuf;
    sendbuf.mtype = SERVERTYPE;

    while (true)
    {
        printf("please enter# ");
        fflush(stdout);
        read(0, sendbuf.mtext, MTEXTSIZE);
        msgsnd(msgid, &sendbuf, strlen(sendbuf.mtext), 0);
    }

    return NULL;
}

int main()
{

    key_t key = ftok(PATHNAME, PROJ_ID);
    printf("%d\n", key);
    if (-1 == key)
    {
        printf("[%d:%s]\n", errno, strerror(errno));
        exit(1);
    }

    int msgid = msgget(key, IPC_CREAT | 0666 | IPC_EXCL);
    if (msgid < 0)
    {
        perror("msgget");
        exit(2);
    }

    pthread_t readtid;
    pthread_create(&readtid, NULL, read_routine, (void *)&msgid);

    pthread_t writetid;
    pthread_create(&writetid, NULL, write_routine, (void *)&msgid);

    pthread_join(readtid, NULL);
    pthread_join(writetid, NULL);

    msgctl(msgid, IPC_RMID, NULL);

    return 0;
}